Kurt Hsu's blog

The Rails developer in taiwan.


  • 首頁

  • 標籤

  • 分類

  • 歸檔

[Rails] I18n 基本使用

發表於 2018-05-14 更新於 2020-05-28 分類於 Rails , i18n

首先安裝rails-i18n

Gemfile
1
gem "rails-i18n"

$ bundle install

我們所有翻譯檔案都會在config/locals目錄下,都是為.yml的檔案,而檔名不重要,純粹是好分辨而已,這邊就創造兩個檔案:
en.yml代表英文翻譯
zh-TW.yml代表中文翻譯

自定義的話例如中文翻譯來說:

1
2
3
4
zh-TW:
welcome: "嗨世界!#{username}"
sport:
ball: 籃球

而英文翻譯:

1
2
3
4
en:
welcome: "Hello world! #{username}"
sport:
ball: basketball

使用方法如下:

example.html.erb
1
2
3
t("sport.ball")
t(:sport, :scope => :ball )
t(:welcome, :username => "Kurt")

在application_controller.rb設定如下:

application_controller.rb
1
2
3
4
5
6
7
8
9
10
before_action :set_locale

def set_locale
# 可以將 ["en", "zh-TW"] 設定為 VALID_LANG 放到 config/environment.rb 中
if params[:locale] && I18n.available_locales.include?( params[:locale].to_sym )
session[:locale] = params[:locale]
end

I18n.locale = session[:locale] || I18n.default_locale
end

在view中切換版本:

example.html.erb
1
2
<%= link_to "中文版", :controller => controller_name, :action => action_name, :locale => "zh-TW" %>
<%= link_to "English", :controller => controller_name, :action => action_name, :locale => "en" %>

I18n 系列:

[Rails] I18n default scope] [Rails] I18n 語系設定]
# Rails # i18n
[Rails]專案引入vue & 利用Attribute給 vue 資料
[Rails]基本Routes設計
  • 文章目錄
  • 本站概要

Kurt Hsu

Progress One Percent Every Day
171 文章
55 分類
163 標籤
RSS
  1. 1. I18n 系列:
© 2020 Kurt Hsu
由 Hexo 強力驅動 v3.8.0
|
主題 – NexT.Muse v7.3.0